<template>
  <div class="conversation-list-container">
    <div class="page-header">
      <h2>谈话记录管理</h2>
      <p>管理用户的谈话记录信息</p>
    </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-blue">
              <el-icon>
                <ChatDotRound />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.totalCount }}</div>
              <div class="stat-label">谈话总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-green">
              <el-icon>
                <User />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.userCount }}</div>
              <div class="stat-label">谈话对象人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-orange">
              <el-icon>
                <Timer />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.avgDuration }}分钟</div>
              <div class="stat-label">平均谈话时长</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon bg-purple">
              <el-icon>
                <Calendar />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statsData.recentDays }}</div>
              <div class="stat-label">最近一次谈话(天)</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="谈话对象">
            <el-input v-model="searchForm.nickName" placeholder="请输入谈话对象姓名" clearable
              @clear="handleInputClear('nickName')" @input="debounceSearch" />
          </el-form-item>
          <el-form-item label="谈话主题">
            <el-input v-model="searchForm.talkTitle" placeholder="请输入谈话主题" clearable
              @clear="handleInputClear('talkTitle')" @input="debounceSearch" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchConversations">
              <el-icon>
                <Search />
              </el-icon> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon>
                <Refresh />
              </el-icon> 重置
            </el-button>
            <el-button type="success" @click="handleAdd">
              <el-icon>
                <Plus />
              </el-icon> 新增谈话记录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 谈话记录列表表格 -->
    <el-card class="table-card" shadow="hover" v-loading="loading">
      <el-table :data="conversationList" border style="width: 100%" row-key="id">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="nickName" label="谈话对象" min-width="100" />
        <el-table-column prop="talkTitle" label="谈话主题" min-width="150" />
        <el-table-column prop="talkTime" label="谈话日期" min-width="120" />
        <el-table-column prop="talkPlace" label="谈话地点" min-width="120" />
        <el-table-column prop="talkDuration" label="谈话时长(分钟)" min-width="120" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" plain @click="handleView(scope.row)">
                <el-icon>
                  <View />
                </el-icon> 查看
              </el-button>
              <el-button size="small" type="warning" plain @click="handleEdit(scope.row)">
                <el-icon>
                  <Edit />
                </el-icon> 编辑
              </el-button>
              <el-button size="small" type="danger" plain @click="handleDelete(scope.row)">
                <el-icon>
                  <Delete />
                </el-icon> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看谈话详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="谈话详情" width="800px" :close-on-click-modal="false">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="谈话对象">{{ currentConversation.nickName }}</el-descriptions-item>
        <el-descriptions-item label="谈话主题">{{ currentConversation.talkSummary }}</el-descriptions-item>
        <el-descriptions-item label="谈话日期">{{ currentConversation.talkTime }}</el-descriptions-item>
        <el-descriptions-item label="谈话地点">{{ currentConversation.talkPlace || '-' }}</el-descriptions-item>
        <el-descriptions-item label="谈话内容" :span="2">
          <div class="conversation-content">
            {{ currentConversation.talkSummary || '暂无内容' }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item v-if="currentConversation.fileUrl" label="谈话记录附件" :span="2">
          <div class="file-preview">
            <!-- 图片文件预览 -->
            <template v-if="isImageFile(currentConversation.fileUrl)">
              <el-image :src="currentConversation.fileUrl" :preview-src-list="[currentConversation.fileUrl]"
                fit="contain" style="max-width: 100%; max-height: 300px; cursor: pointer;">
                <template #error>
                  <div class="file-error">
                    <el-icon>
                      <Picture />
                    </el-icon>
                    <div>图片加载失败</div>
                  </div>
                </template>
              </el-image>
              <div class="file-actions">
                <div class="file-tip">点击图片可全屏查看</div>
                <el-button type="primary" @click="downloadFile(currentConversation.fileUrl)">
                  <el-icon>
                    <Download />
                  </el-icon> 下载图片
                </el-button>
              </div>
            </template>

            <!-- 非图片文件 -->
            <template v-else>
              <div class="document-preview">
                <el-icon class="document-icon">
                  <Document />
                </el-icon>
                <div class="document-name">{{ getFileName(currentConversation.fileUrl) }}</div>
                <el-button type="primary" @click="downloadFile(currentConversation.fileUrl)">
                  <el-icon>
                    <Download />
                  </el-icon> 下载附件
                </el-button>
              </div>
            </template>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/编辑谈话记录对话框 -->
    <el-dialog v-model="editDialogVisible" :title="isEdit ? '编辑谈话记录' : '新增谈话记录'" width="800px"
      :close-on-click-modal="false">
      <el-form :model="conversationForm" :rules="conversationFormRules" ref="conversationFormRef" label-width="100px">
        <el-form-item label="谈话对象" prop="name">
          <template v-if="isEdit">
            <el-input v-model="conversationForm.name" placeholder="请输入姓名" disabled />
          </template>
          <template v-else>
            <el-select v-model="conversationForm.userId" filterable placeholder="请选择谈话对象" @change="handleUserChange">
              <el-option v-for="user in userList" :key="user.id" :label="user.name || user.nickname || user.username"
                :value="user.id" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="谈话主题" prop="result">
          <el-input v-model="conversationForm.result" placeholder="请输入谈话主题" />
        </el-form-item>
        <el-form-item label="谈话日期" prop="date">
          <el-date-picker v-model="conversationForm.date" type="datetime" placeholder="请选择谈话日期"
            format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="谈话地点" prop="location">
          <el-input v-model="conversationForm.location" placeholder="请输入谈话地点" />
        </el-form-item>
        <el-form-item label="谈话时长" prop="duration">
          <el-input-number v-model="conversationForm.duration" :min="1" :max="300" placeholder="请输入谈话时长(分钟)"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="谈话内容" prop="content">
          <el-input v-model="conversationForm.content" type="textarea" :rows="5" placeholder="请输入谈话内容" />
        </el-form-item>
        <el-form-item label="附件" prop="fileUrl">
          <div v-if="conversationForm.fileUrl" class="file-preview-container">
            <!-- 图片文件预览 -->
            <template v-if="isImageFile(conversationForm.fileUrl)">
              <el-image :src="conversationForm.fileUrl" :preview-src-list="[conversationForm.fileUrl]" fit="contain"
                class="preview-image">
                <template #error>
                  <div class="file-error">
                    <el-icon>
                      <Picture />
                    </el-icon>
                    <div>图片加载失败</div>
                  </div>
                </template>
              </el-image>
              <div class="file-tip">点击图片可全屏查看</div>
            </template>

            <!-- 非图片文件预览 -->
            <template v-else>
              <div class="document-preview">
                <el-icon class="document-icon">
                  <Document />
                </el-icon>
                <div class="document-name">{{ getFileName(conversationForm.fileUrl) }}</div>
              </div>
            </template>

            <div class="file-actions">
              <el-button type="danger" @click="conversationForm.fileUrl = ''">
                <el-icon>
                  <Delete />
                </el-icon> 删除附件
              </el-button>
              <el-button type="primary" @click="showUploadDialog = true">
                <el-icon>
                  <Upload />
                </el-icon> 更换附件
              </el-button>
            </div>
          </div>
          <div v-else class="upload-container">
            <el-input v-model="conversationForm.fileUrl" placeholder="请输入文件URL或上传文件" clearable />
            <div class="upload-options">
              <el-button type="primary" @click="showUploadDialog = true" style="margin-top: 10px;">
                <el-icon>
                  <Upload />
                </el-icon> 上传文件
              </el-button>
              <div class="upload-tip">支持 doc、docx 等格式文件，大小不超过1MB</div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitConversation" :loading="submitting">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文件上传对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传文件" width="500px">
      <el-alert type="info" :closable="false" show-icon>
        <p>上传地址: /api/user/uploadImage</p>
        <p>参数名: file</p>
        <p>文件大小限制: 1MB</p>
      </el-alert>
      <el-upload class="upload-demo" drag action="/api/user/uploadImage" name="file" :headers="uploadHeaders"
        :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
        :show-file-list="true" :limit="1" :file-list="fileList">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 jpg、png、pdf、doc、docx 等格式文件，大小不超过1MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showUploadDialog = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search, Refresh, View, Edit, Delete, Plus, ChatDotRound, User, Timer, Calendar,
  Picture, Document, Upload, UploadFilled, Download
} from '@element-plus/icons-vue';
import {
  getConversationList,
  getConversationCount,
  getConversationDetail,
  saveOrUpdateConversation,
  deleteConversation
} from '@/api/conversation';
import { getUserList } from '@/api/user';
import { getUserInfo } from '@/api/auth';
import { useStore } from 'vuex';

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const conversationList = ref([]);

// 统计数据
const statsData = reactive({
  totalCount: 0,
  userCount: 0,
  avgDuration: 0,
  recentDays: 0
});

// 搜索表单
const searchForm = reactive({
  nickName: '',
  talkTitle: '',
  talkTime: '',
  talkPlace: '',
  talkDuration: '',
  talkSummary: ''
});

// 详情对话框
const viewDialogVisible = ref(false);
const currentConversation = ref({});

// 编辑对话框
const editDialogVisible = ref(false);
const isEdit = ref(false);
const conversationFormRef = ref(null);
const conversationForm = reactive({
  id: '',
  userId: null,
  name: '',
  theme: '',
  content: '',
  date: '',
  location: '',
  participants: '',
  result: ''
});
const submitting = ref(false);

// 表单校验规则
const conversationFormRules = {
  name: [{ required: true, message: '请输入谈话对象姓名', trigger: 'blur' }],
  result: [{ required: true, message: '请输入谈话主题', trigger: 'blur' }],
  date: [{ required: true, message: '请选择谈话日期', trigger: 'change' }],
  location: [{ required: true, message: '请输入谈话地点', trigger: 'blur' }],
  duration: [{ required: true, message: '请输入谈话时长', trigger: 'blur' }],
  content: [{ required: true, message: '请输入谈话内容', trigger: 'blur' }]
};

// 文件上传相关
const showUploadDialog = ref(false);
const fileList = ref([]);
const uploadHeaders = {
  // 如果需要附加token等认证信息，可以在这里添加
};

// 用户列表
const userList = ref([]);

// 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await getUserList();
    if (response.data.code === 200) {
      userList.value = response.data.data.users || [];
    } else {
      console.error('获取用户列表失败:', response.data.msg);
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
  }
};

// 初始化加载数据
onMounted(() => {
  fetchConversations();
  fetchUserList(); // 获取用户列表
});

// 获取谈话记录列表
const fetchConversations = async () => {
  loading.value = true;
  try {
    const response = await getConversationList({
      nickName: searchForm.nickName,
      talkTitle: searchForm.talkTitle,
      talkTime: searchForm.talkTime,
      talkPlace: searchForm.talkPlace,
      talkDuration: searchForm.talkDuration,
      talkSummary: searchForm.talkSummary
    }, currentPage.value, pageSize.value);

    if (response.data.code === 200) {
      const records = response.data.data.page.records || [];
      total.value = response.data.data.page.total || 0;

      conversationList.value = records;

      // 更新统计数据
      updateStatsData();
    } else {
      ElMessage.error(response.data.msg || '获取谈话记录列表失败');
    }
  } catch (error) {
    console.error('获取谈话记录列表失败:', error);
    ElMessage.error('获取谈话记录列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 更新统计数据
const updateStatsData = () => {
  // 计算总数
  statsData.totalCount = conversationList.value.length;

  // 计算涉及的谈话对象人数（去重）
  const uniqueNames = new Set();
  conversationList.value.forEach(item => { uniqueNames.add(item.nickName) });
  statsData.userCount = uniqueNames.size;

  // 计算平均谈话时长
  let totalDuration = 0;
  conversationList.value.forEach(item => {
    totalDuration += item.talkDuration || 0;
  });
  statsData.avgDuration = conversationList.value.length ? Math.round(totalDuration / conversationList.value.length) : 0;

  // 计算最近一次谈话距今的天数
  if (conversationList.value.length > 0) {
    // 找出最新的谈话日期
    const dates = conversationList.value.map(item => new Date(item.talkTime));
    const latestDate = new Date(Math.max(...dates));
    const today = new Date();
    const timeDiff = today - latestDate;
    statsData.recentDays = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
  } else {
    statsData.recentDays = 0;
  }
};

// 搜索谈话记录
const searchConversations = () => {
  currentPage.value = 1;
  fetchConversations();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
  fetchConversations();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchConversations();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchConversations();
};

// 处理输入框清除
const handleInputClear = (key) => {
  searchForm[key] = '';
  fetchConversations();
};

// 获取谈话类型名称
const getConversationTypeName = (type) => {
  const types = {
    motivation: '入党动机谈话',
    report: '思想汇报谈话',
    development: '发展谈话',
    regular: '转正谈话',
    other: '其他谈话'
  };
  return types[type] || type;
};

// 查看谈话详情
const handleView = async (row) => {
  try {
    const response = await getConversationDetail(row.id);
    if (response.data.code === 200) {
      console.log(response.data.data);
      currentConversation.value = response.data.data.talkInfo;

      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || '获取谈话详情失败');
    }
  } catch (error) {
    console.error('获取谈话详情失败:', error);
    ElMessage.error('获取谈话详情失败，请稍后重试');
  }
};

// 新增谈话记录
const handleAdd = () => {
  isEdit.value = false;
  Object.keys(conversationForm).forEach(key => {
    if (key === 'duration') {
      conversationForm[key] = 60;
    } else {
      conversationForm[key] = '';
    }
  });
  editDialogVisible.value = true;
};

// 编辑谈话记录
const handleEdit = (row) => {
  isEdit.value = true;
  // 清空表单，防止串数据，然后进行显式映射
  Object.keys(conversationForm).forEach(key => {
    if (typeof conversationForm[key] === 'number') {
      conversationForm[key] = 0; // 或者根据实际情况设为 null 或其他默认值
    } else if (typeof conversationForm[key] === 'boolean') {
      conversationForm[key] = false;
    } else {
      conversationForm[key] = '';
    }
  });

  conversationForm.id = row.id;
  conversationForm.userId = row.userId;
  // 谈话对象姓名，row.name 是经过 getUserInfo 处理得到的，可以直接使用
  conversationForm.name = row.name || row.nickName || '';
  conversationForm.result = row.talkTitle || ''; // 谈话主题
  conversationForm.date = row.talkTime || '';     // 谈话日期
  conversationForm.location = row.talkPlace || ''; // 谈话地点
  conversationForm.duration = row.talkDuration || 60; // 谈话时长，默认60分钟
  conversationForm.content = row.talkSummary || '';   // 谈话内容
  conversationForm.fileUrl = row.fileUrl || '';     // 附件URL

  editDialogVisible.value = true;

};

// 删除谈话记录
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除"${row.nickName}"的谈话记录吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteConversation(row.id);

      if (response.data.code === 200) {
        ElMessage.success('删除谈话记录成功');
        fetchConversations(); // 重新加载列表
      } else {
        ElMessage.error(response.data.msg || '删除谈话记录失败');
      }
    } catch (error) {
      console.error('删除谈话记录失败:', error);
      ElMessage.error('删除谈话记录失败，请稍后重试');
    }
  }).catch(() => { });
};

// 提交谈话记录
const submitConversation = async () => {
  if (!conversationFormRef.value) return;

  conversationFormRef.value.validate(async (valid) => {
    if (!valid) return;

    submitting.value = true;
    try {
      // 构建提交数据
      const submitData = {
        id: conversationForm.id,
        userId: conversationForm.userId,
        applicantId: localStorage.getItem('userId'),
        nickName: conversationForm.nickName,
        talkTitle: conversationForm.result,
        talkTime: conversationForm.date,
        talkPlace: conversationForm.location,
        talkDuration: conversationForm.duration,
        talkSummary: conversationForm.content,
        fileUrl: conversationForm.fileUrl
      };

      const response = await saveOrUpdateConversation(submitData);

      if (response.data.code === 200) {
        ElMessage.success(isEdit.value ? '更新谈话记录成功' : '添加谈话记录成功');
        editDialogVisible.value = false;
        fetchConversations(); // 重新加载列表
      } else {
        ElMessage.error(response.data.msg || (isEdit.value ? '更新失败' : '添加失败'));
      }
    } catch (error) {
      console.error('提交谈话记录失败:', error);
      ElMessage.error('提交失败，请稍后重试');
    } finally {
      submitting.value = false;
    }
  });
};

// 即时搜索
const debounceSearch = () => {
  fetchConversations();
};

// 处理图片预览
const handlePreviewImage = () => {
  if (!conversationForm.fileUrl) {
    ElMessage.warning('请先输入图片URL');
    return;
  }

  // 创建一个临时的图片元素来验证URL
  const img = new Image();
  img.onload = () => {
    // 创建图片预览
    const previewImage = new Image();
    previewImage.src = conversationForm.fileUrl;
    const newWindow = window.open('');
    newWindow.document.write(previewImage.outerHTML);
    newWindow.document.title = '图片预览';
    newWindow.document.close();
  };

  img.onerror = () => {
    ElMessage.error('图片URL无效或无法访问');
  };

  img.src = conversationForm.fileUrl;
};

// 判断是否为图片文件
const isImageFile = (fileUrl) => {
  return fileUrl.endsWith('.jpg') || fileUrl.endsWith('.png') || fileUrl.endsWith('.jpeg');
};

// 获取文件名
const getFileName = (fileUrl) => {
  console.log('获取文件名:', fileUrl);
  const parts = fileUrl.split('/');

  return parts[parts.length - 1];
};

// 打开文件
const openFile = (fileUrl) => {
  window.open(fileUrl, '_blank');
};

// 处理文件预览
const handlePreviewFile = () => {
  if (!conversationForm.fileUrl) {
    ElMessage.warning('请先输入文件URL');
    return;
  }

  if (isImageFile(conversationForm.fileUrl)) {
    // 如果是图片，使用预览功能
    handlePreviewImage();
  } else {
    // 如果是非图片文件，直接打开
    window.open(conversationForm.fileUrl);
  }
};

// 文件上传前的验证
const beforeUpload = (file) => {
  const validTypes = ['image/jpeg', 'image/png', 'application/pdf', 'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
  const isValidType = validTypes.includes(file.type);
  if (!isValidType) {
    ElMessage.error('只能上传JPG、PNG、PDF、DOC、DOCX格式的文件!');
    return false;
  }

  const isLt1M = file.size / 1024 / 1024 < 1;
  if (!isLt1M) {
    ElMessage.error('文件大小不能超过1MB! SpringBoot默认限制为1MB');
    return false;
  }

  return true;
};

// 处理上传成功
const handleUploadSuccess = (response, file, uploadFileList) => {
  console.log('上传响应:', response);
  if (response.code === 200) {
    ElMessage.success('文件上传成功');
    // 设置文件URL到表单中，后端返回的是 {imgUrl: '图片地址'} 格式
    if (response.data && response.data.imgUrl) {
      conversationForm.fileUrl = response.data.imgUrl;
      // 关闭上传对话框
      showUploadDialog.value = false;
    } else {
      ElMessage.warning('获取文件路径失败');
    }
  } else {
    ElMessage.error(response.msg || '文件上传失败');
  }
  // 清空文件列表
  fileList.value = [];
};

// 处理上传错误
const handleUploadError = (error, file, fileList) => {
  console.error('上传错误:', error);
  if (error.status === 404) {
    ElMessage.error('上传接口不存在(404)，请检查API路径是否正确');
  } else if (error.status === 401) {
    ElMessage.error('上传失败(401)，可能是未授权访问');
  } else {
    ElMessage.error(`文件上传失败，错误码: ${error.status || '未知'}`);
  }
  // 清空文件列表
  fileList.value = [];
};

// 下载文件
const downloadFile = (fileUrl) => {
  if (!fileUrl) {
    ElMessage.warning('文件URL不存在');
    return;
  }

  try {
    const prefix = "http://127.0.0.1:8081//"
    const nFileUrl = prefix + fileUrl;
    // 创建一个临时的a标签
    const link = document.createElement('a');
    link.href = nFileUrl;
    link.target = '_blank';

    console.log(nFileUrl)


    // 从URL中提取文件名
    const fileName = getFileName(fileUrl);
    link.download = fileName;

    // 添加到body
    document.body.appendChild(link);

    // 触发点击
    link.click();

    // 移除元素
    document.body.removeChild(link);

    ElMessage.success('下载请求已发送');
  } catch (error) {
    console.error('下载文件失败:', error);
    ElMessage.error('下载文件失败，请稍后重试');
  }
};

// 处理用户选择变化
const handleUserChange = (userId) => {
  if (!userId) {
    conversationForm.name = '';
    conversationForm.userId = null;
    return;
  }

  const selectedUser = userList.value.find(user => user.id === userId);
  if (selectedUser) {
    conversationForm.name = selectedUser.name || selectedUser.nickname || selectedUser.username;
    conversationForm.userId = selectedUser.id;
  }
};
</script>

<style scoped>
.conversation-list-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.conversation-content,
.conversation-result {
  white-space: pre-line;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.action-buttons .el-button {
  margin-left: 0 !important;
  width: 100%;
}

@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-card-content {
  display: flex;
  align-items: center;
  height: 100px;
  padding: 0 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 28px;
  color: white;
}

.bg-blue {
  background-color: #409EFF;
}

.bg-green {
  background-color: #67C23A;
}

.bg-orange {
  background-color: #E6A23C;
}

.bg-purple {
  background-color: #909399;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.file-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.file-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.file-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.image-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.image-preview-container {
  display: flex;
  align-items: center;
}

.preview-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 10px;
}

.file-preview-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.file-preview-container .preview-image {
  width: 200px;
  height: 200px;
  object-fit: contain;
  margin: 0 auto 10px;
}

.file-actions {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 10px;
  gap: 15px;
}

.document-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.document-icon {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 5px;
}

.document-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
}

.upload-container {
  display: flex;
  flex-direction: column;
}

.upload-options {
  display: flex;
  flex-direction: column;
}

.upload-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}
</style>